package com.yjd.bi.report.control;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.yjd.bi.authority.vo.AuthorityUtil;
import com.yjd.bi.comm.vo.Constant;
import com.yjd.bi.report.dto.WeeklyReportItem;
import com.yjd.bi.report.model.ReportWeeklyModel;
import com.yjd.bi.report.service.IReportWeeklyService;
import com.yjd.bi.system.service.ISysParamService;
import com.yjd.comm.annotation.DateString;
import com.yjd.comm.annotation.ServiceRemoteProxy;
import com.yjd.comm.base.control.BaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.PagerHtmlModel;
import com.yjd.comm.rpm.RpmServiceKeyEnum;
import com.yjd.comm.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.Map;

/**
 * 报表相关操作（如：周报）
 * Created by yangchangyan@yijiedai.com on 2018/1/9.
 */
@Controller
@Scope("prototype")
@RequestMapping("/report")
public class ReportControl extends BaseControl {

    @ServiceRemoteProxy(serviceUrlResouceKey = RpmServiceKeyEnum.RPM_BI_SERVICE_KEY)
    private IReportWeeklyService reportWeeklyService;

    @ServiceRemoteProxy(serviceUrlResouceKey = RpmServiceKeyEnum.RPM_BI_SERVICE_KEY)
    private ISysParamService sysParamService;

    @RequestMapping("/weekly/list")
    public String weeklyList() throws Exception {
        Map<String, Object> paramMap = ServletUtil.getPageParameterMap(request);
        paramMap.put("sort", "create_time desc");
        PagerHtmlModel pager = PagerUtil.getPagerHtmlModel(
                this.reportWeeklyService.getPageModel(paramMap, DbWREnums.READ), paramMap,
                ServletUtil.getUrl("/report/weekly/list"));

        List<ReportWeeklyModel> reports = pager.getPagerModel().getDataList();
        for(ReportWeeklyModel r : reports){
            r.getStrMap().put("start_date", DateUtil.getFormate(r.getStart_date(), DateUtil.PATTERN_yyyy_MM_dd));
            r.getStrMap().put("end_date", DateUtil.getFormate(r.getEnd_date(), DateUtil.PATTERN_yyyy_MM_dd));
            r.getStrMap().put("create_time", DateUtil.timestampToDateString(r.getCreate_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
            r.getStrMap().put("update_time", DateUtil.timestampToDateString(r.getUpdate_time(), DateUtil.PATTERN_yyyy_MM_dd_HH_mm_ss));
        }

        boolean addAuthityFlay = false;
        if( super.getLoginUser().getUsername().equalsIgnoreCase("admin")){
            addAuthityFlay = true;
        }

        request.setAttribute("authityFlay", addAuthityFlay);
        request.setAttribute("addReportFlay", AuthorityUtil.authorityValidate(super.getLoginUserId(), Constant.AuthorityEnum.CREATE));
        request.setAttribute("maps", paramMap);
        request.setAttribute("pager", pager);
        return "weekly.list";
    }

    @RequestMapping("/weekly/detail")
    public String weeklyDetail(Long id) throws Exception {

        Assert.isTrue(AuthorityUtil.authorityValidate(super.getLoginUserId(), Constant.AuthorityEnum.RETRIEVE), "您没有权限查看此周报，请联系管理员。");
        Assert.notNull(id, "ID不能为空");
        ReportWeeklyModel report = reportWeeklyService.getModelById(id, DbWREnums.READ);
        Assert.notNull(id, "此周报信息不完整，无法显示。");

        request.setAttribute("id", report.getId());
        request.setAttribute("forbidEdit", "true");
        request.setAttribute("report", report.getReport_content());

        //将20180101的long型转为2018-01-01
        String startDate = DateUtil.getFormateStringByTimeDimention(report.getStart_date(), DateUtil.PATTERN_yyyy_MM_dd);
        String endDate = DateUtil.getFormateStringByTimeDimention(report.getEnd_date(), DateUtil.PATTERN_yyyy_MM_dd);
        request.setAttribute("start", startDate);
        request.setAttribute("end", endDate);

        return "weekly.edit";
    }

    @RequestMapping("/weekly/edit")
    public String weeklyEdit(Long id) throws Exception {
        if (null == id){
            String reportDom = sysParamService.getValueByKey(Constant.SysParamKeyEnum.WEEKLY_REPORT_DOM_STRUCTURE);
            request.setAttribute("forbidEdit", "false");
            request.setAttribute("report", reportDom);
            return "weekly.edit";
        }

        Assert.isTrue(AuthorityUtil.authorityValidate(super.getLoginUserId(), Constant.AuthorityEnum.UPDATE), "您没有权限操作。");
        Assert.notNull(id, "ID不能为空");
        ReportWeeklyModel report = reportWeeklyService.getModelById(id, DbWREnums.READ);
        Assert.notNull(id, "此周报信息不完整，无法显示。");

        request.setAttribute("id", report.getId());
        request.setAttribute("forbidEdit", "false");
        request.setAttribute("report", report.getReport_content());

        //将20180101的long型转为2018-01-01
        String startDate = DateUtil.getFormateStringByTimeDimention(report.getStart_date(), DateUtil.PATTERN_yyyy_MM_dd);
        String endDate = DateUtil.getFormateStringByTimeDimention(report.getEnd_date(), DateUtil.PATTERN_yyyy_MM_dd);
        request.setAttribute("start", startDate);
        request.setAttribute("end", endDate);

        return "weekly.edit";
    }

    /**
     *
     * @param id 周报id
     * @param start
     * @param end
     * @param report 周报内容
     * @return
     * @throws Exception
     */
    @RequestMapping("/weekly/edit/submit")
    public String weeklyEditSubmit(Long id, @DateString String start, @DateString String end, WeeklyReportItem report) throws Exception {
        if(null == report){
            FrameUtil.throwBaseException1("信息不完整");
        }

        if (StringUtils.isBlank(start) && StringUtils.isBlank(end)) {
            FrameUtil.throwBaseException1("报表开始与结束时间未选择");
        }

        Long currentTime = FrameUtil.getTime();
        // 新添加周报
        if(null == id){
            Assert.isTrue(AuthorityUtil.authorityValidate(super.getLoginUserId(), Constant.AuthorityEnum.CREATE), "您没有权限新增周报。");
            ReportWeeklyModel model = new ReportWeeklyModel();
            model.setReport_content(JSON.toJSONString(report, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero));
            model.setCreate_time(currentTime);
            model.setUpdate_time(currentTime);
            model.setStart_date(Long.parseLong(start));
            model.setEnd_date(Long.parseLong(end));
            this.reportWeeklyService.insert(model);
        }
        // 更新原来的周报
        else {
            Assert.isTrue(AuthorityUtil.authorityValidate(super.getLoginUserId(), Constant.AuthorityEnum.UPDATE), "您没有权限修改周报。");
            ReportWeeklyModel model = reportWeeklyService.getModelById(id, DbWREnums.READ);
            Assert.notNull(model, "更新失败");
            model.setReport_content(JSON.toJSONString(report));
            model.setUpdate_time(currentTime);
            model.setStart_date(Long.parseLong(start));
            model.setEnd_date(Long.parseLong(end));
            this.reportWeeklyService.update(model);
        }

        return "redirect:/report/weekly/list.action";
    }

    @RequestMapping("/weekly/delete")
    public void weeklyDelete(Long id) throws Exception {
        if( !super.getLoginUser().getUsername().equalsIgnoreCase("admin")){
            this.errorMsg("没有权限操作");
            return;
        }
        this.reportWeeklyService.delete(id);
        this.successMsg("删除成功");
    }

}
